<template>
  <div class="package-model-container ">
    <div class="package-desc flex-normal">
      <i class="desc-icon el-icon-info"></i>
      <span class="desc-txt">根据套餐内容计算，无需手工输入</span>
    </div>
    <div class="model-main-container">
      <div class="model-tab-container flex-between">
        <div class="model-tab-content flex-normal">
          <div v-for="(tab, idx) in tabList" :key="idx" 
            :class="['tab-item flex-center', currentTab.name == tab.name && 'active']"
            @click="tabChange(tab)">
            <span class="tab-txt">{{tab.label}}</span>
          </div>
        </div>
        <div class="mdoel-btn-content flex-center">
          <span class="btn-txt" @click="showDialog" :loading="glfwProps.queryGl">管理服务</span>
        </div>
      </div>
      <div class="model-main-content" v-if="currentTab.name">
        <!-- <vue-scroll> -->
          <div class="item flex-between" v-for="(item) in currentTab.list" :key="item.id">
            <div class="item-image">
              <img class="image" :src="item.serveImg" >
            </div>
            <div class="item-content flex-column">
              <span class="item-label">{{item.serveName}}</span>
              <span class="item-type">{{item.serveDetails}}</span>
              <div class="item-more flex-normal">
                <span class="i-desc">市场单价：{{item.price || '0.00'}}</span>
                <span class="i-desc">核销价：{{item.writeOffFee || '0.00'}}</span>
              </div>
            </div>
            <div :class="['item-action flex-normal', item.isChecked && 'active']"
            @click="actionItem(item)">
              <span class="action-icon car-common-icon">&#xe663;</span>
              <span class="action-txt">选择</span>
            </div>
          </div>
        <!-- </vue-scroll> -->
      </div>
      <div class="model-selected-content flex-column">
        <span class="select-label">已选服务</span>
        <div class="select-content">
          <el-table :data="tableData" height="300"
            style="width: 100%;">
            <el-table-column prop="serveName" label="服务名称"></el-table-column>
            <el-table-column prop="serveDetails" label="服务内容"></el-table-column>
            <el-table-column prop="inventoryNum" label="数量">
              <template slot-scope="{row}">
                <div>{{ row.inventoryNum || '0' }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格"></el-table-column>
            <el-table-column prop="writeOffFee" label="核销价"></el-table-column>
            <el-table-column prop="total" label="总计"></el-table-column>
          </el-table>
          <div class="sums-content flex-column">
            <div class="sums-item flex-normal">
              <span class="sums-label desc">市场单价</span>
              <span class="sums-val">{{sumsObj.marketPrice}}</span>
            </div>
            <div class="sums-item flex-normal">
              <span class="sums-label">优惠</span>
              <span class="sums-val error">{{sumsObj.preferentialPrice}}</span>
            </div>
            <div class="sums-item flex-normal">
              <span class="sums-label">核销价</span>
              <span class="sums-val">{{sumsObj.writeOffPrice}}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <dialog-normal
      ref="dialog-glfw" class="zjfw-dialog-content"
      :dialog-prop="{
        title: '管理自建服务',
        height: '55vh',
        width: '70%',
        submit: '',
        close: ''
      }"
      @normal-submit="submitDialog('glfw', dialogGlfw.currentItem)">
      <template #dialog-content v-if="$refs[`dialog-glfw`] && $refs[`dialog-glfw`].showDialog">
        <div class="zjfw-dialog-title flex-between">
          <span class="title-txt">自建服务</span>
          <el-button type="text" size="small" icon="el-icon-plus" @click="addItem">新增</el-button>
        </div>
        <div class="app-table-container" v-loading="glfwProps.loading">
          <el-table :data="glfwProps.list" border>
            <el-table-column
              label="服务类型"
              align="center"
              prop="serveTypeId">
              <template slot-scope="{row}">
                <el-select v-model="row['serveTypeId']" placeholder="选择服务类型">
                  <el-option
                    v-for="item in glfwProps.dictTypeList"
                    :key="item.id" filterable
                    :label="item.serveType"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              label="服务名称"
              align="center"
              prop="serveName">
              <template slot-scope="{row}">
                <el-input type="text" size="small" v-model="row.serveName" placeholder="服务名称"/>
              </template>
            </el-table-column>
            <el-table-column
              label="服务明细"
              align="center"
              prop="serveDetails">
              <template slot-scope="{row}">
                <el-input type="text" size="small" v-model="row.serveDetails" placeholder="输入服务明细"/>
              </template>
            </el-table-column>
            <el-table-column
              label="服务次数"
              align="center"
              prop="itemNum">
              <template slot-scope="{row}">
                <el-input type="text" size="small" v-model="row.itemNum" placeholder="输入服务次数"/>
              </template>
            </el-table-column>
            <el-table-column
              label="市场单价"
              align="center"
              prop="price">
              <template slot-scope="{row}">
                <el-input type="text" size="small" v-model="row.price" placeholder="输入市场单价"/>
              </template>
            </el-table-column>
            <el-table-column
              label="核销价"
              align="center"
              prop="writeOffFee">
              <template slot-scope="{row}">
                <el-input type="text" size="small" v-model="row.writeOffFee" placeholder="输入核销价"/>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="{row,$index}">
                <el-button
                  size="mini"
                  type="text" v-if="!row.isEdit"
                  @click="editItem(row)"
                  >编辑</el-button>
                <el-button
                  size="mini"
                  type="text" v-else :loading="row.isSave"
                  @click="saveItem(row)"
                  >保存</el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="delItem(row, $index)"
                  >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </dialog-normal>
  </div>
</template>

<script>
// {
//   activeId: '12',
//   drawList: [{}, {}, {}],
//   pageConf: {}
// }


import {
  buildOneselfServe
} from "@/api/activeManage/active";

import {
  getServeTypeDict, buildOneselfServeList
} from "@/api/common/index";

import {
  addServe, editServe, delServe
} from "@/api/activeManage/serve";
import {isDecimal} from '@/utils/tools.js'
let tabList = [
  {label: '官方服务', name: 'gffw', query: {}, list: []},
  {label: '自建服务', name: 'zjfw', query: {type: 1}, list: []},
]
// serveTypeIds
export default {
  name: 'packageModel',
  components: {
    "dialog-normal": () => import("@/rhComponents/dialog/normal-dialog"),
  },
  props: {
    params: {
      type: Object,
      default: {},
    }
  },
  watch: {
    'params.serveTypeIds': {
      handler(str){
        console.log(this.params, 'params.serveTypeIds')
      },
    }
  },
  computed: {
    tableData(){
      let list = [], list_checked = []
      this.tabList.forEach(tab =>{
        list = [...list, ...tab.list]
      })
      list_checked = list.filter(i => i.isChecked)
      list_checked.forEach(item => {
        this.$set(item, 'total', this.computedRowTotal(item))
        this.$set(item, 'scTotal', this.computedRowScTotal(item))
      })
      this.computedSums(list_checked)
      return list_checked
    },
  },
  data() {
    return {
      tabList: tabList,
      currentTab: tabList[0],
      checkedArr: [], //选中套餐
      sumsObj: {
        serveTypeIds: '',
        marketPrice: '0.00',
        preferentialPrice: '0.00',
        writeOffPrice: '0.00'
      },
      glfwProps: {
        queryGl: false,
        list: [],
        loading: false,
        total: 0,
        queryParams: {
          // pageNum: 1,
          // pageSize: 10,
          type: 1
        },
        dictTypeList: [],
      }
      
    }
  },
  mounted(){
    let _self = this
    let { 
      serveTypeIds = '', 
      marketPrice = '0.00',
      preferentialPrice = '0.00',
      writeOffPrice = '0.00'
    } = _self.params
    _self.sumsObj = {serveTypeIds, marketPrice, preferentialPrice, writeOffPrice}
    _self.getServeList()
    _self.queryServeTypeDict()
  },
  methods: {
    // 自建/官方服务
    getServeList(){
      let _self = this
      buildOneselfServeList(_self.currentTab.query).then(res => {
        let {data} = res, {serveTypeIds = ''} = _self.sumsObj
        let ids = serveTypeIds.split(',')
        _self.currentTab.list = data.map(i => {
          return {
            id: i.id,
            inventoryNum: i.inventoryNum,
            serveImg: i.serveImg,
            serveName: i.serveName,
            serveDetails: i.serveDetails,
            price: i.price,
            writeOffFee: i.writeOffFee,
            isChecked: ids.includes(`${i.id}`)
          }
        })
      })
    },
    tabChange(tab){
      let _self = this
      _self.currentTab = tab
      _self.getServeList()
    },
    computedRowTotal(row){
      let total = parseFloat(row.writeOffFee)
      return total.toFixed(2)
    },
    computedRowScTotal(row){
      let total = parseFloat(row.price)
      return total.toFixed(2)
    },
    computedSums(list){
      let _self = this, obj = {marketPrice: '0.00', preferentialPrice: '0.00', writeOffPrice: '0.00'}
      list.forEach(item => {
        obj.writeOffPrice = parseFloat(obj.writeOffPrice) + parseFloat(item.total)
        obj.marketPrice = parseFloat(obj.marketPrice) + parseFloat(item.scTotal)
      })
      obj.preferentialPrice = parseFloat(obj.marketPrice) - parseFloat(obj.writeOffPrice)
      let ids = list.map(i => i.id).join(',')
      _self.sumsObj = {..._self.sumsObj, ...obj, ...{serveTypeIds: ids}}
      _self.$emit('change', _self.sumsObj)
    },
    validateNum(value){
      let reg = /^\d+$/
      if (!reg.test(value) || value == '0') return false
      return true
    },
    actionItem(item){
      let _self = this, list = []
      _self.$set(item, 'isChecked', !item.isChecked)
    },
    rowNumChange(e, row){
      let _self = this
      let {innerText} = e.target
      let boo = _self.validateNum(innerText)
      if(!boo) {
        _self.sumsObj = {
          scj: '--', yhj: '--', hxj: '--'
        }
        return _self.$message.error('请输入大于0的整数')
      }
      _self.$set(row, 'inventoryNum', innerText)
    },
    async getGlfwList(){
      let _self = this, isSuccess = false
      _self.glfwProps.loading = true
      await buildOneselfServeList(_self.glfwProps.queryParams).then(res => {
        _self.glfwProps.list = res.data || []
        // _self.glfwProps.total = res.total
        isSuccess = true
      })
      _self.glfwProps.loading = false
      return isSuccess
    },
    showDialog(){
      let _self = this
      _self.glfwProps.queryGl = true
      _self.$nextTick(async () => {
        let isSuccess = await _self.getGlfwList()
        if(isSuccess){
          _self.$refs['dialog-glfw'].showDialog = true
        }
        _self.glfwProps.queryGl = false
      })
    },
    /** 查询用户列表 */
    async queryServeTypeDict() {
      let _self = this, isSuccess = false
      await getServeTypeDict()
      .then((res) => {
        isSuccess = true
        _self.glfwProps.dictTypeList = res.data
      })
      return isSuccess
    },
    addItem(){
      let _self = this
      let item = {
        isEdit: true,
        serveTypeId: '',
        serveName: '',
        serveDetails: '',
        itemNum: '1',
        writeOffFee: '0.00',
        price: '0.00',
      }
      _self.glfwProps.list.push(item)
    },
    editItem(row){
      this.$set(row, 'isEdit', true)
    },
    async saveItem(row){
      let _self = this, {serveTypeId, serveName, serveDetails, itemNum, writeOffFee, price} = row
      let reg = /^\d+$/, apiFn = Function
      if(!serveTypeId) return _self.$message.error('服务类型不能为空')
      if(!serveName) return _self.$message.error('服务名称不能为空')
      if(!serveDetails) return _self.$message.error('服务明细不能为空')
      if(!reg.test(itemNum)) return _self.$message.error('请输入正确服务次数')
      if(!isDecimal(writeOffFee)) return _self.$message.error('请输入正确核销价')
      if(!isDecimal(price)) return _self.$message.error('请输入正确市场单价')
      if(!row.id){
        apiFn = addServe
      }else {
        apiFn = editServe
      }
      _self.$set(row, 'isSave', true)
      await apiFn(row).then(res => {
        _self.$set(row, 'isEdit', false)
        _self.getServeList()
      })
      _self.$set(row, 'isSave', false)
    },
    /** 删除按钮操作 */
    delItem(row, index) {
      let id = row.id, _self = this
      if(!id){
        _self.glfwProps.list.splice(index, 1)
      }else{
        this.$modal
        .confirm('是否确认删除？')
        .then(function () {
          return delServe(id);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          _self.getGlfwList()
          return _self.getServeList()
        })
        .catch(() => {});
      }
      
    },
  }
}
</script>

<style lang="scss" scoped>
.package-model-container{
  user-select: none;
  .i-desc{
    margin-right: vw(8);
    &:last-child{
      margin-right: 0;
    }
  }
  .package-desc{
    .desc-icon{
      color: #F7B212;
    }
    .desc-txt{
      margin-left: vw(10);
      font-size: vh(12);
      color: #7F7F7F;
    }
  }
  .model-main-container{
    margin-top: vh(20);
    .model-tab-container{
      .mdoel-btn-content{
        width: vw(90);
        height: vh(36);
        background: rgba(26, 148, 255, 0.08);
        cursor: pointer;
        .btn-txt{
          color: #0003AA;
          font-size: 13px;
        }
      }
      .tab-item{
        width: vw(110);
        height: vh(36);
        background-color: transparent;
        cursor: pointer;
        transition: .2s;
        &.active{
          background-color: rgba(26, 148, 255, 0.08);
          .tab-txt{
            color: #0003AA;
          }
        }
        .tab-txt{
          font-size: 13px;
        }
      }
    }
    .model-main-content{
      margin-top: vh(8);
      border: 1px solid #DDDDDD;
      padding: 0 0 vw(25) vw(25);
      height: vh(300);
      overflow-y: scroll;
      .item{
        margin-top: vh(10);
        padding: 0 vw(42) vh(15) 0;
        .item-image{
          width: vw(80);
          height: vh(60);
          margin-right: vw(25);
          border-radius: vh(6);
          overflow: hidden;
          background-color: rgba(26, 148, 255, 0.08);
          .image{
            display: block;
            height: 100%;
            width: 100%;
          }
        }
        .item-content{
          flex: 1;
          line-height: 1.8;
          .item-label{
            color: #3E3E3E;
            font-size: 13px;
          }
          .item-type, .item-more{
            color: #666666;
            font-size: vh(12);
          }
        }
        .item-action{
          cursor: pointer;
          transition: .2s;
          &.active{
            .action-txt, .action-icon{
              color: #0003AA;
            }
          }
          .action-icon{
            color: #666666;
          }
          .action-txt{
            color: #3E3E3E;
            font-size: 13px;
            margin-left: vw(10);
          }
        }
      }
    }
  }
  .model-selected-content{
    margin-top: vh(20);
    .select-label{
      color: #0003AA;
      font-size: 13px;
    }
    .select-content ::v-deep{
      min-height: vh(330);
      border: 1px solid #DDDDDD;
      .el-table .el-table__header-wrapper th{
        font-size: 13px;
        color: #666;
        font-weight: normal;
      }
      .el-table{
        font-size: 13px;
        color: #3E3E3E;
      }
      .sums-content{
        align-items: flex-end;
        padding: vh(25) vw(40);
        .sums-item{
          margin-top: vh(10);
          &:first-child{
            margin-top: 0;
          }
          .sums-label{
            font-size: vh(12);
            color: #3E3E3E;
            width: vw(100);
            text-align: right;
            margin-right: vw(40);
            &.desc{
              color: #666666;
            }
          }
          .sums-val{
            font-size: vh(12);
            color: #3E3E3E;
            width: vw(100);
            &.error{
              color: #E2231A;
            }
          }
        }
      }
    }
  }
}
.zjfw-dialog-content ::v-deep{
  .title-txt{
    font-size: 16px;
    color: #0003AA;
    font-weight: 500;
  }
  .app-table-container{
    padding: 0;
  }
  .el-input__inner{
    border-color: transparent !important;
  }
}
</style>
